package controllers;

import authentication.IMembershipProvider;
import br.com.caelum.vraptor.Result;
import services.UserRoles;

public abstract class BaseController {

    protected final Result result;
    private final IMembershipProvider membershipProvider;
    private String userName;
    private boolean isAdmin;

    public String getUserName() {
        return userName;
    }

    public boolean isAdmin() {
        return isAdmin;
    }

    public IMembershipProvider getMembershipProvider() {
        return membershipProvider;
    }

    protected BaseController(Result result, IMembershipProvider membershipProvider) {
        this.result = result;
        this.membershipProvider = membershipProvider;

        setUserInfo();
    }

    private void setUserInfo(){
        if(membershipProvider.isAuthenticated()){
            userName = membershipProvider.userName();
            isAdmin =  membershipProvider.inRole(UserRoles.ADMIN_ROLE);
            result.include("user", userName);
            result.include("isAdmin", isAdmin);
        }else{
            userName = null;
        }
    }

}
